package com.jwell.driverapp.tools

import android.content.Intent
import android.widget.Toast
import com.google.gson.JsonObject
import com.jwell.cargoapp.ui.base.IBaseView
import com.jwell.panrank.R
import com.jwell.panrank.application.App
import com.jwell.panrank.ui.activity.LoginActivity
import org.json.JSONObject
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription

/**
 * Created by 76577 on 2018/3/12.
 */

/**
 * 观察者
 */
abstract class BaseSubscriber(private var baseView: IBaseView? = null) : Subscriber<JsonObject> {
    override fun onSubscribe(s: Subscription) {
        if (!Utils.isNetworkAvailable()) {
            //网络错误
            baseView?.hideProgress()
            onFailed(App.instance.resources.getString(R.string.net_disable))
            s.cancel()
        }
        setSubscription(s)
        s.request(Long.MAX_VALUE)
    }

    //取消网络请求
    abstract fun setSubscription(s: Subscription)

    override fun onNext(t: JsonObject?) {
        var jsonObject = JSONObject(t.toString())
        if (App.DEBUG) println(jsonObject)
        if (jsonObject.getBoolean("success")) {
            try {
                succeed(jsonObject)
            } catch (e: Exception) {
                e.printStackTrace()
                onFailed(e.toString())
            }
        } else {
            var jsonObject1 = JSONObject(jsonObject.getString("error"))
            if (jsonObject1.getString("message") == ("Current user did not login to the application!")) {
                onFailed("当前用户没有登录，请重新登录")
                Toast.makeText(App.instance, "由于您太长时间没登录，请重新登录", Toast.LENGTH_SHORT).show()
                var intent = Intent(App.instance, LoginActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                App.instance.startActivity(intent)
            } else {
                onFailed(jsonObject1.getString("message"))
            }
        }
    }

    override fun onError(t: Throwable?) {
        baseView?.hideProgress()
        t?.printStackTrace()
        onFailed(t?.message.toString())
    }

    override fun onComplete() {
        baseView?.hideProgress()
    }

    abstract fun succeed(data: JSONObject)

    abstract fun onFailed(msg: String)

}